
//ui优化
//8.19，9.14
console.show();

auto.waitFor();

console.info('初始化成功!欢迎选择顶瓜瓜旗下脚本，付费版将不受任何限制');

device.keepScreenOn(3600 * 1000);

// 全局常量和配置
const STORAGE_KEY = 'ppmt_2.0';
const DEFAULT_REFRESH_RATE = 400; // 刷新频率间隔
const DEFAULT_JUMP_1 = 400; // 确定-点击后等待间隔
const DEFAULT_JUMP_2 = 200; // 确认信息并支付-点击后等待间隔
const DEFAULT_JUMP_3 = 800; // 就是这家/确认无误-点击后等待间隔
const UI_COLORS = {
    START: '#514dbdff',
    STOP: '#5a4141ff',
    MOVE: '#FF6633',
    SETTING: '#84adea',
    REFRESH: '#dbb95aff',
    CONFIG: '#413737ff',
    TEXT_PRIMARY: '#FFFFFF',
    TEXT_SECONDARY: '#1F1F1F',
};
const TEXT_ELEMENTS = {
    BUY_BTN: '立即购买',
    CONFIRM_BTN: '确定',
    PAY_INFO: '确认信息并支付',
    STORE_PICKUP: '到店取',
    HOME_DELIVERY: '送到家',
    STORE_CONFIRM: '就是这家',
    DELIVERY_CONFIRM: '确认无误',
    IN_STOCK: '到货通知',
    BOX: '整盒',
};

// 创建存储
let storage = storages.create('ppmt_2.0');

// 版本检测
//const { roomName, isBright, sleepNum } = hamibot.env;

let isVersion = 'a';

// 通用变量
// 按钮坐标
let x2 = storage.get('x2');
let y2 = storage.get('y2');
let x3 = storage.get('x3');
let y3 = storage.get('y3');
let x4 = storage.get('x4');
let y4 = storage.get('y4');

// 运行状态
let isRunning = false;
let mainThread = null;
let mainThread2 = null;
let isRun = false; // 是否进入循环点击模式

// 配置
let deliveryMethod = TEXT_ELEMENTS.STORE_PICKUP;
let buyBtn = TEXT_ELEMENTS.STORE_CONFIRM;
let refresh = storage.get('refresh') || DEFAULT_REFRESH_RATE;

// 使用音频路径
let filePath = '/sdcard/npSound.mp3';

// 通用函数
/**
 * 切换按钮文本和颜色
 * @param {object} btn - 按钮对象
 * @param {string} text - 要设置的文本
 * @param {string} color - 要设置的颜色
 */
function changeFontText(btn, text, color, icon) {
    // 处理默认参数
    if (typeof icon === 'undefined') icon = '';

    // 添加图标前缀
    var displayText = icon ? icon + ' ' + text : text;

    btn.setText(displayText);
    btn.setBackgroundColor(android.graphics.Color.parseColor(color));

    // 添加视觉反馈动画效果（如果支持）
    try {
        btn.animate()
            .scaleX(0.95)
            .scaleY(0.95)
            .setDuration(100)
            .withEndAction(function () {
                btn.animate().scaleX(1.0).scaleY(1.0).setDuration(100).start();
            })
            .start();
    } catch (e) {
        // 如果动画不支持，忽略错误
    }
}

/**
 * 校准按钮坐标
 * @param {string} buttonText - 按钮文本
 * @param {number} timeout - 查找超时时间
 * @returns {object|null} - 按钮对象或null
 */
function calibrateButton(buttonText, timeout) {
    let btn = className('android.widget.TextView')
        .text(buttonText)
        .findOne(timeout || 500);
    if (!btn) return null;

    let centerX = btn.bounds().centerX();
    let centerY = btn.bounds().centerY();

    console.log(`${buttonText}按钮坐标: ${centerX}, ${centerY}`);
    return { x: centerX, y: centerY, btn: btn };
}

/**
 * 设置移动按钮的触摸监听器
 * @param {object} window - 窗口对象
 * @param {object} offset - 偏移量对象
 */
function setMoveButtonListener(window, offset) {
    window.moveBtn.setOnTouchListener(function (_, event) {
        switch (event.getAction()) {
            case event.ACTION_DOWN:
                offset.x = event.getRawX() - window.getX();
                offset.y = event.getRawY() - window.getY();
                break;
            case event.ACTION_MOVE:
                let newX = event.getRawX() - offset.x;
                let newY = event.getRawY() - offset.y;
                window.setPosition(newX, newY);
                break;
        }
        return true;
    });
}

// 下载音乐
const downloadMusic = () => {
    // 检查文件是否存在
    if (files.isFile(filePath)) return;

    let music_url = 'https://usedcar-1313455168.cos.ap-guangzhou.myqcloud.com/5353_0f0f_0358_d99739615f8e5153d77042092f07fd77.mp3';

    // 添加请求头模拟浏览器访问
    let res = http.get(music_url, {
        headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        },
    });

    if (res.statusCode != 200) return toastLog('下载音乐失败');

    // 写入绝对路径
    files.writeBytes(filePath, res.body.bytes());
    toastLog('下载响铃完成')
};

// 播放音乐
const playMusic = () => {
    try {
        media.playMusic(filePath);
        device.vibrate(3600 * 1000);

        setTimeout(() => {
            media.stopMusic();
            device.cancelVibration();
        }, 5000);
    } catch (e) {
        toastLog('播放异常: ' + e);
    }
};

if (isVersion == 'a') {
    

    threads.start(function(){

    //线程
   downloadMusic();
    

})

    // 新版UI
    
// 监听通知
//roomName
if (1>2) {
    try {
        events.observeNotification();

        console.info(`准备监听群聊名称:${roomName}`);

        events.onNotification((notification) => {
            if (roomName != '' && notification.title == roomName) {
                const text = notification.getText();

                if (text.indexOf('送到家') != -1) {
                    deliveryMethod = TEXT_ELEMENTS.HOME_DELIVERY;

                    buyBtn = TEXT_ELEMENTS.DELIVERY_CONFIRM;

                    stopScript();

                    if (mainThread != null && mainThread.isAlive()) {
                        mainThread.interrupt();
                    }

                    console.log('已选择取货方式: ' + deliveryMethod);

                    // 更新取货方式按钮文本
                    if (resetWindow.deliveryBtn) {
                        var deliveryIcon = deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? '🏪' : '🚚';
                        var deliveryText = deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? '到店取' : '送到家';
                        resetWindow.deliveryBtn.setText(deliveryIcon + ' ' + deliveryText);
                    }
                }

                if (text.indexOf('到店取') != -1) {
                    deliveryMethod = TEXT_ELEMENTS.STORE_PICKUP;

                    buyBtn = TEXT_ELEMENTS.STORE_CONFIRM;

                    stopScript();

                    if (mainThread != null && mainThread.isAlive()) {
                        mainThread.interrupt();
                    }

                    console.log('已选择取货方式: ' + deliveryMethod);

                    // 更新取货方式按钮文本
                    if (resetWindow.deliveryBtn) {
                        var deliveryIcon = deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? '🏪' : '🚚';
                        var deliveryText = deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? '到店取' : '送到家';
                        resetWindow.deliveryBtn.setText(deliveryIcon + ' ' + deliveryText);
                    }
                }

                if (text.indexOf('数量1') != -1) {
                    if (isPlus == 0) return;

                    stopScript();

                    isPlus = 0;

                    storage.put('isPlus', isPlus);

                    let num = Number(isPlus) + 1;

                    changeFontText(resetWindow.isPlusBtn, '数量+' + num, UI_COLORS.SETTING);
                }

                if (text.indexOf('数量2') != -1) {
                    if (isPlus == 1) return;

                    stopScript();

                    isPlus = 1;

                    storage.put('isPlus', isPlus);

                    let num = Number(isPlus) + 1;

                    changeFontText(resetWindow.isPlusBtn, '数量+' + num, UI_COLORS.SETTING);
                }

                if (text.indexOf('启动') != -1) {
                    notification.click();

                    console.info('监听到启动命令');

                    sleep(1000);

                    console.info('开始识别小程序');

                    let miniArr = className('android.widget.TextView').id('bit').depth(28).text('小程序').find();

                    let index = 1;

                    let getMiniArr = () => {
                        index++;

                        console.log('尝试获取小程序!' + index);

                        if (index < 10 && miniArr.empty()) {
                            miniArr = className('android.widget.TextView').id('bit').depth(28).text('小程序').find();

                            if (miniArr.empty()) {
                                sleep(300);

                                getMiniArr();
                            } else {
                                return true;
                            }
                        } else {
                            home();

                            console.error('获取小程序失败');

                            return false;
                        }
                    };

                    if (miniArr.empty() && !getMiniArr()) return;

                    let x = miniArr[miniArr.length - 1].bounds().centerX();

                    let y = miniArr[miniArr.length - 1].bounds().centerY();

                    click(x, y);

                    startScript();
                }

                if (text.indexOf('停止') != -1) {
                    stopScript();

                    home();

                    console.info('脚本已停止!');
                }
            }
        });
    } catch (e) {
        toast('请手动打开通知权限：打开Hamibot→点击左上角→打开通知读取权限');
    }
}

    let isCollapsed = false;

   // 创建悬浮窗按钮
let resetWindow = floaty.rawWindow(
    <frame gravity="center" w="*" h="*">
        <vertical>
            
            <button id="moveBtn" text="拖动" w="60" h="40" bg="#2ecc71" textColor="#ffffff" textSize="10sp" layout_margin="2dp" />

            <button id="startBtn" text=" 开始" w="60" h="40" bg="#3498db" textColor="#ffffff" textSize="10sp" layout_margin="2dp" />

            <vertical id="collapsibleContent">
                <button id="configBtn" text=" 配置" w="60" h="40" bg="#f1c40f" textColor="#ffffff" textSize="10sp" layout_margin="2dp" />

                <button id="isPlusBtn" text="数量+2" w="60" h="40" bg="#9b59b6" textColor="#ffffff" textSize="10sp" layout_margin="2dp" />

                <button id="deliveryBtn" text=" 到店取" w="60" h="40" bg="#e67e22" textColor="#ffffff" textSize="10sp" layout_margin="2dp" />
                <button id="configBtn1" text=" 停止" w="60" h="40" bg="#e74c3c" textColor="#ffffff" textSize="10sp" layout_margin="2dp" />
           
            </vertical>

            <button id="foldBtn" text="折叠菜单" w="60" h="40" bg="#34495e" textColor="#ffffff" textSize="10sp" layout_margin="2dp" />
        </vertical>
    </frame>
);


    // 设置按钮位置
    resetWindow.setPosition(device.width - 220, device.height / 4);

    // 新版特有变量
    let mainThread3 = null; // 到货通知线程
    let mainThread4 = null; // 端盒线程
    let mainThread5 = null; // 取货方式线程
    let mainThread6 = null; // 付款响铃线程
    let mainThread7 = null; // 自动输入密码

    // 外部配置
    let isPlus = isNaN(storage.get('isPlus')) ? 1 : Number(storage.get('isPlus')); // 商品数量是否+2
    let isInform = isNaN(storage.get('isInform')) ? 1 : Number(storage.get('isInform')); // 默认点到货通知
    let isBox = isNaN(storage.get('isBox')) ? 1 : Number(storage.get('isBox')); // 端盒选择
    let isRing = isNaN(storage.get('isRing')) ? 0 : Number(storage.get('isRing')); // 是否响铃
    let isAround = isNaN(storage.get('isAround')) ? 1 : Number(storage.get('isAround')); // 是否开启左右刷新
    let PayCode = storage.get('PayCode') == undefined ? '' : storage.get('PayCode'); // 支付密码
    

    // 跳转间隔
    let jump_1 = storage.get('jump_1') || DEFAULT_JUMP_1;
    let jump_2 = storage.get('jump_2') || DEFAULT_JUMP_2;
    let jump_3 = storage.get('jump_3') || DEFAULT_JUMP_3;

    // 移动按钮
    let moveOffset = { x: 0, y: 0 };
    setMoveButtonListener(resetWindow, moveOffset);

    // 开始
    resetWindow.startBtn.on('click', function () {
        if (!x2 || !y2 || !x3 || !y3 || !x4 || !y4) return dialogs.alert('请先完成按钮校准!');
        if (!isRunning) startScript();
        else stopScript();
    });

       let lastClickTime = 0; // 记录上次点击时间
resetWindow.configBtn1.on('click', function () {
 // stopScript()
 //toastLog("凭借订单号加QQ群165460925")
     const currentTime = new Date().getTime();
    // 计算与上次点击的时间差
     toast("双击关闭脚本");
    if (currentTime - lastClickTime < 500) { // 500毫秒内视为双击
        toast("已关闭脚本");
        exit(); // 执行退出
    }
    lastClickTime = currentTime; // 更新最后点击时间
//app.openUrl("https://www.123865.com/s/Ml2djv-IdCfh");
});

    // 配置
    resetWindow.configBtn.on('click', function () {
        stopScript();

        dialogs.select('请选择需要设置的功能:', ['刷新频率间隔', '默认点到货通知', '校准的按钮', '端盒的选择', '精准的间隔', '支付的响铃', '是否开启左右刷新']).then(function (i) {
            switch (Number(i)) {
                case 0:
                    dialogs.prompt('请输入刷新频率间隔(毫秒)', refresh, function (input) {
                        if (isNaN(input)) return console.error('输入值无效!!');
                        if (Number(input) < 150) return;
                        refresh = Number(input);
                        storage.put('refresh', Number(input));
                        console.log('刷新频率间隔已设置为: ' + refresh + '毫秒');
                    });
                    break;
                case 1:
                    dialogs
                        .build({
                            title: '默认点到货通知',
                            items: ['否', '是'],
                            itemsSelectMode: 'single',
                            itemsSelectedIndex: Number(isInform),
                        })
                        .on('single_choice', function (index) {
                            isInform = index;
                            storage.put('isInform', index);
                            console.log('默认点到货通知: ' + (Number(isInform) ? '是' : '否'));
                        })
                        .show();
                    break;
                case 2:
                    handleCalibration();
                    break;
                case 3:
                    dialogs
                        .build({
                            title: '端盒选择',
                            items: ['否', '是'],
                            itemsSelectMode: 'single',
                            itemsSelectedIndex: Number(isBox),
                        })
                        .on('single_choice', function (index) {
                            isBox = index;
                            storage.put('isBox', index);
                            console.log('端盒选择: ' + (Number(isBox) ? '是' : '否'));
                        })
                        .show();
                    break;
                case 4:
                    handleIntervalSettings();
                    break;
                case 5:
                    dialogs
                        .build({
                            title: '抢到了是否需要响铃',
                            items: ['否', '是'],
                            itemsSelectMode: 'single',
                            itemsSelectedIndex: Number(isRing),
                        })
                        .on('single_choice', function (index) {
                            isRing = index;
                            storage.put('isRing', index);
                            console.log('是否响铃: ' + (Number(isRing) ? '是' : '否'));
                        })
                        .show();
                    break;

                case 6:
                    dialogs
                        .build({
                            title: '是否开启左右刷新',
                            items: ['否', '是'],
                            itemsSelectMode: 'single',
                            itemsSelectedIndex: Number(isAround),
                        })
                        .on('single_choice', function (index) {
                            isAround = index;
                            storage.put('isAround', index);
                            console.log('是否开启左右刷新: ' + (Number(isAround) ? '是' : '否'));
                        })
                        .show();
                    break;
            }
        });
    });

    // 数量是否+2
    resetWindow.isPlusBtn.on('click', function () {
        stopScript();

        dialogs
            .build({
                title: '商品数量是否+2',
                items: ['否', '是'],
                itemsSelectMode: 'single',
                itemsSelectedIndex: Number(isPlus),
            })
            .on('single_choice', (index) => {
                isPlus = index;
                storage.put('isPlus', index);
                console.log('商品数量是否+2: ' + (Number(isPlus) ? '是' : '否'));
            })
            .show();
    });

    // 取货方式按钮
    resetWindow.deliveryBtn.on('click', function () {
        stopScript();
        handleDeliveryMethodChange();
    });

    // 折叠按钮
    resetWindow.foldBtn.click(() => {
        if (isCollapsed) {
            resetWindow.collapsibleContent.setVisibility(0); // 显示
            resetWindow.foldBtn.setText('折叠面板');
            isCollapsed = false;
        } else {
            resetWindow.collapsibleContent.setVisibility(8); // 隐藏 (GONE)
            resetWindow.foldBtn.setText('展开面板');
            isCollapsed = true;
        }
    });

    // 取货方式选择处理函数
    function handleDeliveryMethodChange() {
        deliveryMethod = deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? TEXT_ELEMENTS.HOME_DELIVERY : TEXT_ELEMENTS.STORE_PICKUP;

        buyBtn = deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? TEXT_ELEMENTS.STORE_CONFIRM : TEXT_ELEMENTS.DELIVERY_CONFIRM;

        changeFontText(resetWindow.startBtn, '开始', UI_COLORS.START, ' ');

        isRunning = false;

        isRun = false;

        if (mainThread != null && mainThread.isAlive()) {
            mainThread.interrupt();
        }

        console.log('已选择取货方式: ' + deliveryMethod);

        // 更新取货方式按钮文本
        if (resetWindow.deliveryBtn) {
            var deliveryIcon = deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? ' ' : ' ';
            var deliveryText = deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? '到店取' : '送到家';
            resetWindow.deliveryBtn.setText(deliveryIcon + ' ' + deliveryText);
        }
    }

    // 按钮校准处理函数
    function handleCalibration() {
        let options = [
            `${TEXT_ELEMENTS.PAY_INFO}-${x2 && y2 ? `已校准-${x2},${y2}` : '未校准'}`,
            `${TEXT_ELEMENTS.STORE_CONFIRM}-${x3 && y3 ? `已校准-${x3},${y3}` : '未校准'}`,
            `${TEXT_ELEMENTS.DELIVERY_CONFIRM}-${x4 && y4 ? `已校准-${x4},${y4}` : '未校准'}`,
        ];

        dialogs.select('请选择校准按钮', options).then((i) => {
            if (i < 0) return;

            let result;
            switch (i + 1) {
                case 1:
                    result = calibrateButton(TEXT_ELEMENTS.PAY_INFO);
                    if (!result) return;
                    storage.put('x2', result.x);
                    storage.put('y2', result.y);
                    x2 = result.x;
                    y2 = result.y;
                    break;
                case 2:
                    result = calibrateButton(TEXT_ELEMENTS.STORE_CONFIRM);
                    if (!result) return;
                    storage.put('x3', result.x);
                    storage.put('y3', result.y);
                    x3 = result.x;
                    y3 = result.y;
                    break;
                case 3:
                    result = calibrateButton(TEXT_ELEMENTS.DELIVERY_CONFIRM);
                    if (!result) return;
                    storage.put('x4', result.x);
                    storage.put('y4', result.y);
                    x4 = result.x;
                    y4 = result.y;
                    break;
            }
        });
    }

    // 间隔设置处理函数
    function handleIntervalSettings() {
        let advancedOptions = ['确定-点击后等待间隔', '确认信息并支付-点击后等待间隔', `${buyBtn}-点击后等待间隔`];

        dialogs.select('请选择需要设置的按钮间隔:', advancedOptions).then((i) => {
            if (i < 0) return;

            let title = advancedOptions[i];
            let setTitle = '';
            let defaultValue = 0;

            switch (i + 1) {
                case 1:
                    setTitle = 'jump_1';
                    defaultValue = jump_1;
                    break;
                case 2:
                    setTitle = 'jump_2';
                    defaultValue = jump_2;
                    break;
                case 3:
                    setTitle = 'jump_3';
                    defaultValue = jump_3;
                    break;
            }

            dialogs.prompt(`请输入${title}(毫秒)`, defaultValue, (input) => {
                if (input == null) return;
                if (isNaN(input)) return console.error('输入值无效!!');

                storage.put(setTitle, Number(input));

                switch (setTitle) {
                    case 'jump_1':
                        jump_1 = Number(input);
                        break;
                    case 'jump_2':
                        jump_2 = Number(input);
                        break;
                    case 'jump_3':
                        jump_3 = Number(input);
                        break;
                }

                console.log(`${title}已设置为: ` + input + '毫秒');
            });
        });
    }
   console.info(`当前配置如下：`);
    console.info(`刷新频率间隔为: ${refresh}毫秒`);
    console.info(`确定等待间隔为: ${jump_1}毫秒`);
    console.info(`确认并支付等待间隔为: ${jump_2}毫秒`);
    console.info(`${buyBtn}等待间隔为: ${jump_3}毫秒`);

    // 停止脚本
    function stopScript() {
        // 判断脚本是否在运行
        if (!isRunning) return;

        changeFontText(resetWindow.startBtn, '开始', UI_COLORS.START);
        isRunning = false;
        isRun = false;
        threads.shutDownAll();
        mainThread = null;
        mainThread2 = null;
        mainThread3 = null;
        mainThread4 = null;
        mainThread5 = null;
        mainThread6 = null;
        mainThread7 = null;
        mainThread8 = null;

        media.stopMusic();
        device.cancelVibration();

        console.log('脚本已关闭');
    }

    // 开始脚本
    function startScript() {
        console.clear();

        changeFontText(resetWindow.startBtn, '关闭', UI_COLORS.STOP, ' ');

        isRunning = true;

        console.log('脚本已开始运行');

        mainThread = threads.start(function () {
            runMainScript();
        });
    }

    // 主要逻辑封装为函数
    function runMainScript() {
        console.log('开始执行脚本...');

        let btn1, btn2, btn3, plus, inform, boxBtn, isFirst;

        // 检测到货通知
        if (isInform) {
            mainThread3 = threads.start(function () {
                console.warn('到货通知检测开启');
                inform = className('android.widget.TextView').text(TEXT_ELEMENTS.IN_STOCK).findOne();
                inform && inform.click();
                mainThread3.interrupt();
                console.info('到货通知线程结束');
            });
        }

        // 端盒选择线程
        if (isBox) {
            mainThread4 = threads.start(function () {
                console.warn('端盒检测开启');
                boxBtn = className('android.widget.TextView').textContains(TEXT_ELEMENTS.BOX).findOne();
                boxBtn && boxBtn.click();
                mainThread4.interrupt();
                console.info('线端盒线程结束');
            });
        }

        // 付款响铃线程
        if (isRing) {
            mainThread6 = threads.start(function () {
                console.warn('付款响铃检测开启');

                id('czu').findOne();

                console.log('下单成功,请付款!🎁');

                playMusic();
            });
        }

        
    // 自动输入密码
    if (PayCode != '') {
        mainThread7 = threads.start(function () {
            console.warn('自动输入密码开启');

            id('czu').findOne();

            let payCodeArray = String(PayCode).split('');

            if (payCodeArray.length != 6) return log('支付密码长度不为6位数,请重新设置!');

            let btn0 = id('tenpay_keyboard_' + payCodeArray[0]).findOne();
            btn0 && btn0.click();

            sleep(500);

            let btn1 = id('tenpay_keyboard_' + payCodeArray[1]).findOne();
            btn1 && btn1.click();

            sleep(500);

            let btn2 = id('tenpay_keyboard_' + payCodeArray[2]).findOne();
            btn2 && btn2.click();

            sleep(500);

            let btn3 = id('tenpay_keyboard_' + payCodeArray[3]).findOne();
            btn3 && btn3.click();

            sleep(500);

            let btn4 = id('tenpay_keyboard_' + payCodeArray[4]).findOne();
            btn4 && btn4.click();

            sleep(500);

            let btn5 = id('tenpay_keyboard_' + payCodeArray[5]).findOne();
            btn5 && btn5.click();

            mainThread7.interrupt();

            console.info('自动输入密码线程结束');
        });
    }

        // 取货方式线程
        mainThread5 = threads.start(function () {
            console.warn('取货方式检测开启');
            deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP
                ? className('android.widget.TextView').text(TEXT_ELEMENTS.STORE_PICKUP).findOne().click()
                : className('android.widget.TextView').text(TEXT_ELEMENTS.HOME_DELIVERY).findOne().click();
            mainThread5.interrupt();
            console.info('取货方式线程结束');
        });

        while (isRunning) {
            try {
                if (!isRun) {
                    // 判断是否需要左右刷新
                    if (isAround) {
                        if (!isFirst) {
                            // 寻找并点击立即购买按钮
                            className('android.widget.TextView').text(TEXT_ELEMENTS.BUY_BTN).findOne().click();
                            isFirst = true;
                        }

                        if (deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP) {
                            className('android.widget.TextView').text(TEXT_ELEMENTS.HOME_DELIVERY).findOne().click();
                        } else {
                            className('android.widget.TextView').text(TEXT_ELEMENTS.STORE_PICKUP).findOne().click();
                        }

                        deliveryMethod = deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? TEXT_ELEMENTS.HOME_DELIVERY : TEXT_ELEMENTS.STORE_PICKUP;

                        buyBtn = deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? TEXT_ELEMENTS.STORE_CONFIRM : TEXT_ELEMENTS.DELIVERY_CONFIRM;

                        // 更新取货方式按钮文本
                        if (resetWindow.deliveryBtn) {
                            var deliveryIcon = deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? ' ' : ' ';
                            var deliveryText = deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? '到店取' : '送到家';
                            resetWindow.deliveryBtn.setText(deliveryIcon + ' ' + deliveryText);
                        }
                    } else {
                        className('android.widget.TextView').text(TEXT_ELEMENTS.BUY_BTN).findOne().click();
                    }

                    // 确定按钮
                    btn1 = className('android.widget.TextView').text(TEXT_ELEMENTS.CONFIRM_BTN).findOne(refresh);

                    // 获取+号控件
                    if (isPlus && !plus) {
                        console.info('正在查找加号控件');
                        const index = className('android.widget.TextView').text('1').depth(25).findOne(20);
                        if (index) {
                            console.info('找到加号控件');
                            plus = className('android.widget.Image')
                                .depth(25)
                                .indexInParent(index.indexInParent() + 1)
                                .findOne(20);
                        } else {
                            console.error('查找失败,加号控件未找到!');
                        }
                    }

                    plus && plus.click();

                    btn1 && btn1.click();
                }

                // 检查是否出现确定按钮
                if (btn1 || isRun) {
                    isRun = true;

                    if (!mainThread2) {
                        console.log('确定按钮点击1 -- 完毕!');

                        sleep(jump_1);

                      click(x2+random(-5,5), y2+random(-5,5));
                        console.log('确认信息支付1 -- 完毕!');

                        sleep(jump_2);

                        buyBtn == TEXT_ELEMENTS.STORE_CONFIRM ? click(x3+random(-5,5), y3+random(-5,5)) : click(x4+random(-5,5), y4+random(-5,5));
                        console.log('就是这家1 -- 完毕!');

                        sleep(jump_3);

                        // 开启确定按钮线程
                        mainThread2 = threads.start(function () {
                            console.info('确定按钮检测线程开启');
                            while (isRun && isRunning) {
                                try {
                                    let btn4 = className('android.widget.TextView').text(TEXT_ELEMENTS.CONFIRM_BTN).findOne(50);
                                    if (btn4) {
                                        btn4.click();
                                        sleep(200); // 点击后短暂等待，避免重复点击
                                    }
                                    sleep(50); // 检测间隔，避免过度消耗CPU
                                } catch (e) {
                                    sleep(100);
                                }
                            }
                            console.warn('线程2检测结束');
                        });

                        btn2 = className('android.widget.TextView').text(TEXT_ELEMENTS.PAY_INFO).findOnce();
                        if (btn2) btn2.click();
                        else continue;
                        console.log('确认信息并支付1.1 -- 完毕!');

                        sleep(jump_2);

                        btn3 = className('android.widget.TextView').text(buyBtn).findOnce();
                        if (btn3) btn3.click();
                        else continue;
                        console.log('就是这家1.1 -- 完毕!');

                        sleep(jump_3);
                    } else {
                        btn2 = className('android.widget.TextView').text('确认信息并支付').findOne(200);
                        if (btn2) btn2.click();
                        else continue;

                        console.log('确认信息并支付2 -- 完毕!');

                        sleep(jump_2);

                        btn3 = className('android.widget.TextView').text(buyBtn).findOnce();
                        if (btn3) btn3.click();
                        else continue;

                        console.log('就是这家2 -- 完毕!');

                        sleep(jump_3);
                    }
                }
            } catch (e) {}
        }
    }
} else {
    // 旧版UI
    let resetWindow = floaty.rawWindow(
        <frame gravity="center" w="*" h="*">
            <vertical>
                <button id="moveBtn" text="移动" w="60" h="40" bg={UI_COLORS.MOVE} textSize="10sp" layout_margin="2dp" />
                <button id="startBtn" text="开始" w="*" h="*" bg={UI_COLORS.START} textColor="#ffffff" textSize="10sp" layout_margin="2dp" />
                <button id="configBtn" text="配置(到店取)" w="*" h="*" bg="#ffffff" textSize="10sp" layout_margin="2dp" />
                <button id="settingBtn" text="校准" w="*" h="*" bg={UI_COLORS.SETTING} textColor="#ffffff" textSize="10sp" layout_margin="2dp" />
                <button id="refreshBtn" text="刷新频率间隔" w="*" h="*" bg={UI_COLORS.REFRESH} textColor="#ffffff" textSize="10sp" layout_margin="2dp" />
            </vertical>
        </frame>
    );

    // 设置按钮位置
    resetWindow.setPosition(device.width - 200, device.height / 2 / 2);

    // 移动按钮
    let moveOffset = { x: 0, y: 0 };
    setMoveButtonListener(resetWindow, moveOffset);

    // 开始
    resetWindow.startBtn.on('click', function () {
        if (!isRunning) startScript();
        else stopScript();
    });

    // 配置
    resetWindow.configBtn.on('click', function () {
        dialogs
            .build({
                title: '请选择取货方式',
                items: [TEXT_ELEMENTS.STORE_PICKUP, TEXT_ELEMENTS.HOME_DELIVERY],
                itemsSelectMode: 'single',
                itemsSelectedIndex: deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? 0 : 1,
            })
            .on('single_choice', (index, item) => {
                deliveryMethod = item;
                buyBtn = deliveryMethod == TEXT_ELEMENTS.STORE_PICKUP ? TEXT_ELEMENTS.STORE_CONFIRM : TEXT_ELEMENTS.DELIVERY_CONFIRM;
                changeFontText(resetWindow.startBtn, '开始', UI_COLORS.START);
                isRunning = false;
                isRun = false;
                if (mainThread != null && mainThread.isAlive()) {
                    mainThread.interrupt();
                }
                console.clear();
                console.log('配置更新成功! 请点击开始按钮重新启动');
                console.log('已选择取货方式: ' + deliveryMethod);
                resetWindow.configBtn.setText(`配置(${deliveryMethod})`);
            })
            .show();
    });

    // 校准
    resetWindow.settingBtn.on('click', function () {
        let options = [
            `${TEXT_ELEMENTS.PAY_INFO}-${x2 && y2 ? `已校准-${x2},${y2}` : '未校准'}`,
            `${TEXT_ELEMENTS.STORE_CONFIRM}-${x3 && y3 ? `已校准-${x3},${y3}` : '未校准'}`,
            `${TEXT_ELEMENTS.DELIVERY_CONFIRM}-${x4 && y4 ? `已校准-${x4},${y4}` : '未校准'}`,
        ];

        dialogs.select('请选择校准按钮', options).then((i) => {
            if (i < 0) return;

            let result;
            switch (i + 1) {
                case 1:
                    result = calibrateButton(TEXT_ELEMENTS.PAY_INFO);
                    if (!result) return;
                    storage.put('x2', result.x);
                    storage.put('y2', result.y);
                    x2 = result.x;
                    y2 = result.y;
                    break;
                case 2:
                    result = calibrateButton(TEXT_ELEMENTS.STORE_CONFIRM);
                    if (!result) return;
                    storage.put('x3', result.x);
                    storage.put('y3', result.y);
                    x3 = result.x;
                    y3 = result.y;
                    break;
                case 3:
                    result = calibrateButton(TEXT_ELEMENTS.DELIVERY_CONFIRM);
                    if (!result) return;
                    storage.put('x4', result.x);
                    storage.put('y4', result.y);
                    x4 = result.x;
                    y4 = result.y;
                    break;
            }
        });
    });

    // 刷新频率间隔
    resetWindow.refreshBtn.on('click', function () {
        // 停止脚本
        stopScript();

        dialogs.prompt('请输入刷新频率间隔(毫秒)', refresh, (input) => {
            if (isNaN(input)) return console.error('输入值无效!!');
            if (Number(input) < 251) return;
            refresh = Number(input);
            console.log('刷新频率间隔已设置为: ' + refresh + '毫秒');
        });
    });

    // 停止脚本
    function stopScript() {
        changeFontText(resetWindow.startBtn, '开始', UI_COLORS.START);
        isRunning = false;
        isRun = false;
        if (mainThread != null && mainThread.isAlive()) mainThread.interrupt();
        if (mainThread2 != null && mainThread2.isAlive()) mainThread2.interrupt();
        mainThread = null;
        mainThread2 = null;
        console.log('脚本已关闭');
    }

    // 开始脚本
    function startScript() {
        console.clear();
        changeFontText(resetWindow.startBtn, '关闭', UI_COLORS.STOP);
        isRunning = true;
        console.log('脚本已开始运行');
        mainThread = threads.start(function () {
            runMainScript();
        });
    }

    // 主要逻辑封装为函数
    function runMainScript() {
        console.log('开始执行脚本...');
        let btn1;

        while (isRunning) {
            try {
                if (!isRun) {
                    let boxBtn = className('android.widget.TextView').textContains(TEXT_ELEMENTS.BOX).findOne(20);
                    boxBtn && boxBtn.click();

                    // 寻找并点击立即购买按钮
                    className('android.widget.TextView').text(TEXT_ELEMENTS.BUY_BTN).findOne().click();

                    // 确定按钮
                    btn1 = className('android.widget.TextView').text(TEXT_ELEMENTS.CONFIRM_BTN).findOne(refresh);

                    btn1 && btn1.click();
                }

                // 检查是否出现确定按钮
                if (btn1 || isRun) {
                    isRun = true;

                    if (!mainThread2) {
                        console.log('确定按钮点击1 -- 完毕!');

                        sleep(200);

                        press(x2, y2, 1);

                        sleep(200);

                        console.log('确认信息并支付1 -- 完毕!');

                        buyBtn == TEXT_ELEMENTS.STORE_CONFIRM ? press(x3, y3, 1) : press(x4, y4, 1);

                        console.log('就是这家1 -- 完毕!');

                        sleep(500);
                    } else {
                        let btn2 = className('android.widget.TextView').text(TEXT_ELEMENTS.PAY_INFO).findOne(200);
                        if (btn2) btn2.click();
                        else continue;
                        console.log('确认信息并支付2 -- 完毕!');
                        sleep(200);

                        let btn3 = className('android.widget.TextView').text(buyBtn).findOne(200);
                        if (btn3) btn3.click();
                        else continue;
                        console.log('就是这家2 -- 完毕!');
                        sleep(200);
                    }

                    if (!mainThread2) {
                        mainThread2 = threads.start(function () {
                            while (isRun && isRunning) {
                                try {
                                    let btn4 = className('android.widget.TextView').text(TEXT_ELEMENTS.CONFIRM_BTN).findOne(50);
                                    if (btn4) {
                                        btn4.click();
                                        sleep(200); // 点击后短暂等待，避免重复点击
                                    }
                                    sleep(50); // 检测间隔，避免过度消耗CPU
                                } catch (e) {
                                    sleep(100);
                                }
                            }
                            console.log('线程2检测结束');
                        });
                    }
                }
            } catch (e) {}
        }
    }
}

// 保持脚本运行状态
setInterval(() => {}, 1000)
//123